package cn.ac.iscas.service.queue;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author LJian
 * @version 1.0
 * @description: TODO
 * @date 2022/7/5 13:53
 */
@Service
public class SqlExecuteQueueService {
    private ConcurrentHashMap<String, ConcurrentLinkedQueue<String>> queue = new ConcurrentHashMap<>(64);

    public boolean add(String jobId, String value) {
        synchronized (this.queue) {
            if (!this.queue.containsKey(jobId)){
                ConcurrentLinkedQueue<String> data = new ConcurrentLinkedQueue<>();
                data.add(value);
                this.queue.put(jobId, data);
                return true;
            } else {
                return this.queue.get(jobId).add(value);
            }
        }
    }

    public boolean add(String jobId, List<String> value) {
        synchronized (this.queue) {
            if (!this.queue.containsKey(jobId)){
                ConcurrentLinkedQueue<String> data = new ConcurrentLinkedQueue<>();
                data.addAll(value);
                this.queue.put(jobId, data);
                return true;
            } else {
                return this.queue.get(jobId).addAll(value);
            }
        }
    }

    public String poll(String jobId) {
        synchronized (this.queue) {
            if (this.queue.containsKey(jobId)) {
                return this.queue.get(jobId).poll();
            } else {
                return null;
            }
        }
    }

    public ConcurrentLinkedQueue<String> getSqlsByJobId(String jobId) {
        return queue.get(jobId);
    }

}
